import Store from "@/store";
import PD from "..";
import { APP_ROUTES } from "@/pd-libs/enum/app-routes";
import type { ACCEPT_ORDER_SOURCE } from "@/pd-libs/enum/pd-enum";
import type { ApiOrderTypes } from "@/api/api-types/api-order-types";
import OrderHelp from ".";
import { useOrderCtrl } from "@/pd-libs/hooks/useOrder";
import type { PDRequest } from "../request";
import Api from "@/api/api-declare";

const {acceptOrderFromSquare : acceptOrderFromSquareApi} = useOrderCtrl();
/**
 * 从订单广场接单，公共逻辑部分全在这里处理
 *   包括以下场景
 * 	 1、从应用首页接单
 */
type AcceptOrderFromSquareOps = {
	order : ApiOrderTypes.OrderDto,//订单信息
	source : ACCEPT_ORDER_SOURCE,//接单来源
	queue_id ?: number
};
export function acceptOrderFromSquare(ops : AcceptOrderFromSquareOps) : Promise<void> {
	return new Promise(async (r, j) => {
		//实名认证校验
		await hasRealNameCheck();
		//如果是顺风车，进行顺风车提醒
		await sfcNotice(ops.order);
		PD.UniHelp.loading();
		acceptOrderFromSquareApi(ops.order, ops.source, ops.queue_id).then(() => {
			PD.UniHelp.loading(false);
			Api.ApiJiaoGuan.YYCF(ops.order.order_num);//交管上报营运出发
			
			r();
		}).catch((err : PDRequest.BaseRes<void>) => {
			PD.UniHelp.loading(false);
			PD.UniHelp.modal({
				title : '接单失败',
				content : err.msg,
				showCancel : false,
			});
			j();
		});
	});
};


export function hasRealNameCheck(): Promise<void> {
	return new Promise((r, j) => {
		if (!Store.driver().isRealNameAuthed) {
			PD.UniHelp.modal({
				title: '认证提醒',
				content: '根据交通运输部相关规定，顺风车司机接单需要进行实名认证。',
				showCancel: false,
				confirmText: '去认证',
			}).then(() => {
				PD.UniHelp.navTo(APP_ROUTES.realNameAuth);
				j();
			});
			return;
		};
		r();
	});
}

export function sfcNotice (order : ApiOrderTypes.OrderDto) : Promise<void> {
	return new Promise((r,j) => {
		if (OrderHelp.Judge.isOnTheWayOrder(order.channel) && !OrderHelp.Judge.isCpInputOrder(order.create_type)) {
			PD.UniHelp.modal({
				title : '接单须知',
				content : '请勿线下交易，线下交易将封号，取消后1小时无法接单',
				cancelText : '不抢了',
				confirmText : '抢单'
			}).then(() => {
				PD.WxHelp.wxReport('orderlist_get_done');
				r();
			}).catch(() => {
				PD.WxHelp.wxReport('orderlist_get_giveup');
				j();
			});
			return;
		};
		r();
	});
}